import { createRouter, createWebHashHistory,createWebHistory } from 'vue-router'
import {getToken} from '@/utils/auth.js'
const routes = [
    { name: '登录', path: '/login', component: () => import('../views/login.vue') },
    {
        name: '首页',
        path: '/',
        component: () => import('../views/home.vue'),
        redirect:'/main',
        children: [
            { name: '首页', path: '/main', component: () => import('../views/main.vue') },
            { name: '文章详情', path: '/article/:id', component: () => import('../views/article.vue') },
            { name: '文章详情-评论', path: '/article/:id/:commentId', component: () => import('../views/article.vue') },
            { name: '添加文章', path: '/addArticle', component: () => import('../views/addArticle.vue') },
            { name: '编辑文章', path: '/updateArticle/:id', component: () => import('../views/updateArticle.vue') },
            { name: '个人主页', path: '/personal', component: () => import('../views/personal.vue') }
        ]

    },
    { name: '关于', path: '/about', component: () => import('../views/about.vue') }
]

// 创建路由实例
const router = createRouter({
    // history: createWebHashHistory(),
    history: createWebHistory(),
    routes //路由表
})


// 需要登录才能使用的路由 
const rules = ['文章详情-评论','添加文章','编辑文章','个人主页'];
router.beforeEach((to,from,next)=>{
    window.document.title = to.name

    const token = getToken('token');
    if(rules.indexOf(to.name)!=-1){
        if(!token){
            return next('/login')
        }
    }
    
    next()
})

export default router
